/**
 *  This file is part of MunchLevel.
 *
 *  MunchLevel is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  MunchLevel is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with MunchLevel.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.munchlevel;

import java.util.LinkedList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;

import com.gandulf.guilib.download.AbstractDownloader;
import com.gandulf.guilib.download.Downloader;
import com.gandulf.guilib.download.DownloaderWrapper;
import com.munchlevel.data.MunchkinConfiguration.Edition;
import com.munchlevel.preference.ListPreferenceMultiSelect;
import com.munchlevel.util.ThemeManager;
import com.munchlevel.util.Util;

public class MyPreferenceActivity extends PreferenceActivity {

	public static final String KEY_WAKE_LOCK = "wakeLock";
	public static final String KEY_THEME = "theme";
	public static final String KEY_DOWNLOAD_THEMES = "downloadThemes";
	public static final String KEY_MAX_LEVEL = "levelMaximum";
	public static final String KEY_TOOLTIPS = "tooltips";
	public static final String KEY_GEAR_COUNTER = "gearCounter";
	public static final String KEY_FULLSCREEN = "fullscreen";
	public static final String KEY_PROFILE_PICTURE = "profilePicture";
	public static final String KEY_SHAKE_DICE = "shakeRollDice";
	public static final String KEY_DICE = "rollDice";
	public static final String KEY_SOUND_EFFECTS = "soundEffects";
	public static final String KEY_DISCLAIMER = "disclaimer";
	public static final String KEY_LEFT_HANDED = "lefthanded";
	public static final String KEY_CLASS_RACE = "classRace";
	public static final String KEY_EDITIONS = "editions";
	public static final String KEY_DONATE = "donate";

	public static final String PATH_THEMES = "http://munch-level.googlecode.com/files/munchlevel-themes.1.zip";

	private AbstractDownloader downloader;

	private ThemeManager themeManager;

	private BroadcastReceiver broadcastReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
		addPreferencesFromResource(R.xml.preferences);

		ListPreference themePreference = (ListPreference) findPreference(KEY_THEME);

		themeManager = new ThemeManager(this);

		List<String> themesValues = themeManager.getThemes();
		List<String> themeNames = new LinkedList<String>();
		for (String themeValue : themesValues) {
			themeNames.add(Util.capitalize(themeValue.replace("_", " ")));
		}

		themePreference.setEntries(themeNames.toArray(new String[0]));
		themePreference.setEntryValues(themesValues.toArray(new String[0]));

		// -- editions
		ListPreferenceMultiSelect editionPreference = (ListPreferenceMultiSelect) findPreference(KEY_EDITIONS);

		List<String> editionValues = new LinkedList<String>();
		List<String> editionNames = new LinkedList<String>();
		for (Edition edition : Edition.values()) {
			editionNames.add(edition.getTitle());
			editionValues.add(edition.name());
		}

		editionPreference.setEntries(editionNames.toArray(new String[0]));
		editionPreference.setEntryValues(editionValues.toArray(new String[0]));

		broadcastReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {

				int result = intent.getIntExtra(Downloader.INTENT_RESULT, -1);

				intent.getSerializableExtra(Downloader.INTENT_EXCEPTION);
				intent.getStringExtra(Downloader.INTENT_ERROR);

				if (result == Downloader.RESULT_OK) {
					themeManager.refreshThemes();
					ListPreference themePreference = (ListPreference) findPreference(KEY_THEME);

					List<String> themesValues = themeManager.getThemes();
					List<String> themeNames = new LinkedList<String>();
					for (String themeValue : themesValues) {
						themeNames.add(Util.capitalize(themeValue.replace("_", " ")));
					}

					themePreference.setEntries(themeNames.toArray(new String[0]));
					themePreference.setEntryValues(themesValues.toArray(new String[0]));
				}

			}
		};

		registerReceiver(broadcastReceiver, new IntentFilter(Downloader.ACTION_UNZIP_COMPLETE));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.preference.PreferenceActivity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		unregisterReceiver(broadcastReceiver);
		themeManager.close();
		super.onDestroy();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seeandroid.preference.PreferenceActivity#onPreferenceTreeClick(android.
	 * preference.PreferenceScreen, android.preference.Preference)
	 */
	@Override
	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
		if (preference.getKey().equals(KEY_DOWNLOAD_THEMES)) {

			downloader = DownloaderWrapper.getInstance(MunchLevelApplication.SD_DIR.getAbsolutePath(), this);
			downloader.addPath(PATH_THEMES);
			downloader.downloadZip();

			return true;
		} else if (preference.getKey().equals(KEY_DONATE)) {
			Uri uriUrl = Uri
					.parse("https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=gandulf%2ek%40gmx%2enet&lc=EN&item_name=Gandulf&item_number=MunchLevel&currency_code=EUR&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHosted");
			final Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
			startActivity(launchBrowser);
			return true;
		}

		return super.onPreferenceTreeClick(preferenceScreen, preference);
	}

}